package hangban.com.maochang.util;



import java.sql.*;


public class BaseDao {
    private final static  String forN="com.mysql.jdbc.Driver";
    private final String url="jdbc:mysql://localhost:3308/AirFei";
    private final String user="root";
    private final String pwd="root";

   static {
       try {
           Class.forName(forN);
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
   }

   public Connection getconn(){
       Connection conn=null;
       try {
            conn = DriverManager.getConnection(url, user, pwd);
       } catch (SQLException e) {
           e.printStackTrace();
       }
       return conn;
   }
   public void closeAll(Connection conn, Statement stmt, ResultSet rs){
       try {
           if(rs!=null){
               rs.close();
           }
           if(stmt!=null){
               stmt.close();
           }
           if(conn!=null){
               conn.close();
           }
       } catch (SQLException e) {
           e.printStackTrace();
       }
   }
   public Boolean update(String sql,Object[] os){
       Connection conn=this.getconn();
       PreparedStatement pstmt=null;
       int row=0;
       try {
            pstmt = conn.prepareStatement(sql);
            if(os!=null){
                for(int i=0;i<os.length;i++){
                    pstmt.setObject(i+1,os[i]);
                }
            }
            row=pstmt.executeUpdate();
       } catch (SQLException e) {
           e.printStackTrace();
       }
       finally {
           closeAll(conn,pstmt,null);
       }
       return row>0;
   }


    public ResultSet query(String sql,Object[] os){
        Connection conn=this.getconn();
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        try {
            pstmt = conn.prepareStatement(sql);
            if(os!=null){
                for(int i=0;i<os.length;i++){
                    pstmt.setObject(i+1,os[i]);
                }
            }
            rs=pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
}
